package com.sparkseries.clean;

import com.sparkseries.dao.SysNoticeMapper;
import com.sparkseries.service.SysLogService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class Clean implements CommandLineRunner {
    @Resource
    private SysLogService logService;
    @Resource
    private SysNoticeMapper sysNoticeMapper;

    private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    // 保留天数，默认为 7 天
    @Value("${clean.retention.days:7}")
    private int retentionDays;

    @Override
    public void run(String... args) {
        scheduleTask(this::cleanLogs, "日志清理任务");
        scheduleTask(this::cleanNotices, "通知清理任务");
        scheduleTask(this::cleanMyNotices, "我的通知清理任务");
    }

    private void scheduleTask(Runnable task, String taskName) {
        try {
            executor.scheduleAtFixedRate(task, 0, 1, TimeUnit.DAYS);
            log.info("{} 已安排为每天执行。", taskName);
        } catch (Exception e) {
            log.error("安排 {} 失败", taskName, e);
        }
    }

    private Date calculateCutoffDate() {
        return new Date(System.currentTimeMillis() - (long) retentionDays * 24 * 60 * 60 * 1000);
    }

    private void cleanLogs() {
        performCleaning(() -> logService.deleteByDate(calculateCutoffDate()), "日志清理任务");
    }

    /**
     * 定期清理已删除的通知
     */
    private void cleanNotices() {
        performCleaning(() -> sysNoticeMapper.deleteNotice(calculateCutoffDate()), "通知清理任务");
    }

    private void cleanMyNotices() {
        performCleaning(() -> sysNoticeMapper.deleteMyNotice(calculateCutoffDate()), "我的通知清理任务");
    }

    private void performCleaning(Runnable cleaningAction, String taskName) {
        try {
            Date cutoffDate = calculateCutoffDate();
            cleaningAction.run();
            log.info("{} 已完成。已删除早于以下日期的记录：{}", taskName, cutoffDate);
        } catch (Exception e) {
            log.error("{} 过程中发生错误", taskName, e);
        }
    }
}